﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Playwright;

namespace Jy.Abp.Playwright;

public class BrowserContextCacheItem : IAsyncDisposable
{
    public BrowserContextCacheItem(string key, IBrowserContext context)
    {
        this.Key = key;
        this.Context = context;
        Trace.WriteLine($"{this.Key}：ContextCache.Create");
    }

    public string Key { get; private set; }

    public event EventHandler<BrowserContextCacheItem> Close;

    public IBrowserContext Context { get; private set; }

    public async Task<IPage> NewPageAsync(string url = null)
    {
        var page = await this.Context.NewPageAsync();
        if (url.HasValue())
            await page.GotoAsync(url);
        return page;
    }

    public async ValueTask DisposeAsync()
    {
        Trace.WriteLine($"{this.Key}：ContextCache.DisposeAsync");

        Close?.Invoke(this, this);

        if (Context.Pages.Count <= 0)
        {
            Trace.WriteLine($"{this.Key}：ContextCache.Context.DisposeAsync");
            await this.Context.DisposeAsync();
        }
    }
}
